package com.jhf.youke.base.domain.service;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.DES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.json.JSONUtil;
import com.jhf.youke.base.domain.converter.AutoCompletedConverter;
import com.jhf.youke.base.domain.gateway.AutoCompletedRepository;
import com.jhf.youke.base.domain.model.Do.AutoCompletedDo;
import com.jhf.youke.base.domain.model.po.AutoCompletedPo;
import com.jhf.youke.base.domain.model.vo.AutoCompletedVo;
import com.jhf.youke.core.ddd.AbstractDomainService;
import com.jhf.youke.core.entity.PageQuery;
import com.jhf.youke.core.entity.Pagination;
import com.jhf.youke.core.utils.CacheUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


/**
 * @author RHJ
 */
@Service
@Log4j2
public class AutoCompletedService extends AbstractDomainService<AutoCompletedRepository, AutoCompletedDo, AutoCompletedVo> {

    private static final String BASE_SERVICE = "base";

    @Resource
    AutoCompletedConverter autoCompletedConverter;

    @Override
    public boolean update(AutoCompletedDo entity) {
        AutoCompletedPo autoCompletedPo = autoCompletedConverter.do2Po(entity);
        autoCompletedPo.preUpdate();
        return repository.update(autoCompletedPo);
    }

    @Override
    public boolean updateBatch(List<AutoCompletedDo> doList) {
        List<AutoCompletedPo> poList = autoCompletedConverter.do2PoList(doList);
        return repository.updateBatch(poList);
    }

    @Override
    public boolean delete(AutoCompletedDo entity) {
        AutoCompletedPo autoCompletedPo = autoCompletedConverter.do2Po(entity);
        return repository.delete(autoCompletedPo);
    }

    @Override
    public boolean deleteBatch(List<Long> idList) {
        return repository.deleteBatch(idList);
    }

    @Override
    public boolean insert(AutoCompletedDo entity) {
        AutoCompletedPo autoCompletedPo = autoCompletedConverter.do2Po(entity);
        autoCompletedPo.preInsert();
        return repository.insert(autoCompletedPo);
    }

    @Override
    public boolean insertBatch(List<AutoCompletedDo> doList) {
        List<AutoCompletedPo> poList = autoCompletedConverter.do2PoList(doList);
        poList = AutoCompletedPo.getInsertListId(poList);
        return repository.insertBatch(poList);
    }

    @Override
    public Optional<AutoCompletedVo> findById(Long id) {
        Optional<AutoCompletedPo> autoCompletedPo =  repository.findById(id);
        AutoCompletedVo autoCompletedVo = autoCompletedConverter.po2Vo(autoCompletedPo.orElse(new AutoCompletedPo()));
        return Optional.ofNullable(autoCompletedVo);
        
    }

    @Override
    public boolean remove(Long id) {
        return repository.remove(id);
    }

    @Override
    public boolean removeBatch(List<Long> idList) {
        return repository.removeBatch(idList);
    }

    @Override
    public List<AutoCompletedVo> findAllMatching(AutoCompletedDo entity) {
        AutoCompletedPo autoCompletedPo = autoCompletedConverter.do2Po(entity);
        List<AutoCompletedPo>autoCompletedPoList =  repository.findAllMatching(autoCompletedPo);
        return autoCompletedConverter.po2VoList(autoCompletedPoList);
    }


    @Override
    public Pagination<AutoCompletedVo> selectPage(AutoCompletedDo entity){
        AutoCompletedPo autoCompletedPo = autoCompletedConverter.do2Po(entity);
        PageQuery<AutoCompletedPo> pageQuery = new PageQuery<>(autoCompletedPo,entity.getCurrentPage(), entity.getPageSize(), entity.getQuerySort());
        Pagination<AutoCompletedPo> pagination = repository.selectPage(pageQuery);
        return new Pagination<>(pagination.getPageNum(),pagination.getPageSize(),pagination.getTotalSize(),
                autoCompletedConverter.po2VoList(pagination.getList()));
    }


    public Map<String,Object> autoCompleted(AutoCompletedDo entity){
        Map<String,Object> map = new HashMap<>(8);
        Optional<AutoCompletedPo> autoCompleted =  repository.findById(entity.getId());
        AutoCompletedDo autoCompletedDo = autoCompletedConverter.po2Do(autoCompleted.orElse(new AutoCompletedPo()));

        Map<String,Object> paramMap = new HashMap<>(8);
        paramMap.put("sql", autoCompletedDo.getSqlstr());

        Integer pageLimit = entity.getPageLimit();
        pageLimit = pageLimit == 0 ? 10 : pageLimit;
        paramMap.put("pageLimit", pageLimit);
        paramMap.put("query", entity.getQuery());
        Long companyId = entity.getCompanyId();
        if(companyId > 0){
            paramMap.put("companyId",companyId);
        }
        Long rootId = entity.getRootId();
        if(rootId > 0){
            paramMap.put("rootId",rootId);
        }

        if(BASE_SERVICE.equals(autoCompletedDo.getServerName())){
            List<Map<String, String>> list = repository.autoCompleteBySql(paramMap);
            map.put("data", list);
        }else{
            String key = "aes_key_" + UUID.randomUUID();
            //随机生成密钥
            byte[] my = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
            log.info("my {}", my);

            //构建
            DES des = SecureUtil.des(my);
            CacheUtils.set(key, Base64.getEncoder().encodeToString(my), 60*20);
            log.info("原sql {}", JSONUtil.toJsonStr(paramMap));
            //加密为16进制表示
            String sql = des.encryptHex(JSONUtil.toJsonStr(paramMap));

            map.put("sql", sql);
            map.put("serverName", autoCompletedDo.getServerName());
            map.put("key",key);
        }

        return map;

    }
}

